library(plyr)
library(estimatr)
library(emmeans)
library(multcomp)
library(tidyverse)
library(magrittr)
library(broom)
library(ggbeeswarm)
library(metafor)

d1 <- "https://github.com/thomasjwood/full_fact/raw/main/ff_mt.rds" %>% 
  url %>% 
  gzcon  %>% 
  readRDS %>% 
  mutate(
    out_agree = out_agree %>% 
      mapvalues(
        c("Tend to disagree",
          "Tend to agree"),
        c("Disagree",
          "Agree")
      ) %>% 
      factor(
        c("Strongly disagree",
          "Disagree",
          "Neither agree nor disagree",
          "Agree",
          "Strongly agree")
      ),
    out_true = out_true %>% 
      factor(
        c("True",
          "Probably true",
          "Not sure",
          "Probably false",
          "False") %>% 
          rev
      ),
    agree_num = out_agree %>% 
      as.numeric,
    true_num = out_true %>% 
      as.numeric,
    cond = cond %>% 
      factor(
        c("cond_items",
          "cond_misinfo",
          "cond_corr")
      )
  )

cor(d1$agree_num, d1$true_num)

d1$com_num <- d1$agree_num %>% 
  add(
    d1$true_num
  ) %>% 
  divide_by(2)

d1$ideo_num <- d1$ideo %>% 
  mapvalues(
    c("Left1", 
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "8",
      "7",
      "9",
      "10",
      "Right10",
      "Prefer not to say", 
      "Don't know",
      "DK"),
    c(1, 1:10, 10, NA, NA, NA)
  ) %>% 
  as.character %>% 
  as.numeric

d1$ideo_cat <- case_when(
  d1$ideo_num %>% 
    is_in(
      1:4
      ) ~ "Left",
  d1$ideo_num %>% 
    is_in(
      5:6
    ) ~ "Moderate",
  d1$ideo_num %>% 
    is_in(
      7:10
    ) ~ "Right"
  ) %>% 
  factor(
    c("Left", "Moderate", "Right")
    )

t1 <- d1 %>% 
  mutate(
    country = issue %>%
      str_detect(
        "global|saltwater"
      ) %>%
      ifelse(
        "multi_country-" %>% 
          str_c(
            country
          ),
        country
      )
  ) %>% 
  filter(
    wave == "wave 1"
  ) %>% 
  group_by(
    country, issue
  ) %>% 
  nest

t1$rm <- t1$data %>% 
  map(
    ~lm_robust(
      com_num ~ cond * ideo_cat,
      .x
      )
    )

t1$em <- t1$rm %>% 
  map(
    ~emmeans(
      .x, 
      consec ~ cond | ideo_cat
      )
  )

t2 <- t1 %>% 
  ungroup %>% 
  select(
    country, issue, em
  ) %>% 
  pmap_dfr(
    function(country, issue, em)
      em %>% 
      extract2(2) %>% 
      tidy %>% 
      mutate(
        country = country,
        issue = issue
      )
  ) %>% 
  mutate(
    contrast = contrast %>% 
      str_detect(
        " cond_items"
      ) %>% 
      ifelse(
        "Misinformation effect",
        "Correction effect"
      ) %>% 
      factor(
        c("Misinformation effect",
          "Correction effect")
        ),
    ideo_cat = ideo_cat %>% 
      fct_inorder,
    c2 = country %>% 
      str_detect("multi") %>% 
      ifelse(
        "Multi-country",
        country
        ) %>% 
      plyr::mapvalues(
        "nigeria", 
        "Nigeria"
        ) %>% 
      factor(
        c("Argentina",
          "Nigeria",
          "South Africa",  
          "United Kingdom",
          "Multi-country",
          "Combined"
          )
      )
    )


t3 <- t2 %>%
  nest_by(
    contrast, c2
    )

t3$rma <- t3$data %>% 
  map(
    ~rma(
      yi = estimate, 
      sei = std.error, 
      mods = ~ factor(ideo_cat) - 1, 
      data = .x
      )
  )

t4 <- t3 %>% 
  ungroup %>% 
  select(-data) %>% 
  pmap_dfr(
    function(
      c2, rma, contrast
    )
      
     # rma <- t3$rma[[1]] 
      
      rma %>% 
      predict.rma(
        newmods = cbind(c(1, 0, 0), c(0, 1, 0), c(0, 0, 1)),
        addx = T
        ) %>% 
      as_tibble %>% 
      mutate(
        # term = term,
        c2 = c2,
        contrast = contrast
      )
  ) %>% 
  mutate(
    ideo_cat = case_when(
      X.factor.ideo_cat.Left == 1 &
      X.factor.ideo_cat.Moderate == 0 & 
      X.factor.ideo_cat.Right == 0  ~ "Left",
      X.factor.ideo_cat.Left == 0 &
      X.factor.ideo_cat.Moderate == 1 & 
      X.factor.ideo_cat.Right == 0  ~ "Moderate",
      X.factor.ideo_cat.Left == 0 &
      X.factor.ideo_cat.Moderate == 0 & 
      X.factor.ideo_cat.Right == 1  ~ "Right"
      ) %>% 
      factor(
        c("Left",
          "Moderate",
          "Right")
      )
  )

t4$lab <- t4$pred %>%  
  round(2) %>% 
  as.character %>% 
  str_replace("0\\.", "\\.")

t4$lab[t4$lab == "0"] <- ".002"

t3 %>% 
  ungroup %>% 
  select(-data) %>%
  rename(rfac = contrast) %>% 
  pmap_dfr(
    function(
      rfac, c2, rma
      )
      rma %>% 
      glht(
        # linfct=cbind(contrMat(rep(1,3), type="Tukey")),
        linfct = rbind(c(-1,  1,  0),
                       c(-1,  0,  1),
                       c( 0, -1,  1)),
        # test=adjusted("none")
      ) %>%
      tidy %>% 
      mutate(
        c2 = c2,
        rfac = rfac
      )
  ) %>%  
  filter(
    adj.p.value < .1
  ) %>% 
  mutate(
    contrast = contrast %>% 
      plyr::mapvalues(
        1:3,
        c(
          "Left - Moderate",
          "Left - Right",
          "Moderate - Right"
        )
      )
  )


t2 %>%
  mutate(
    contrast = contrast %>%
      str_replace(" ", "\n") %>%
      factor(
        c("Misinformation\neffect",
          "Correction\neffect")
        )
  ) %>% 
  ggplot() +
  geom_hline(
    yintercept = 0,
    linetype = "dotted"
  ) +
  geom_beeswarm(
    aes(
      ideo_cat, estimate, 
      color = adj.p.value < .05
    ), 
    size = 2,
    groupOnX = T,
    cex = 5
  ) +
  geom_linerange(
    aes(
      ideo_cat, ymin = ci.lb,
      ymax = ci.ub
    ),
    data = t4 %>% 
      mutate(
        contrast = contrast %>%
          str_replace(" ", "\n") %>%
          factor(
            c("Misinformation\neffect",
              "Correction\neffect")
          )
      )
    ) +
  geom_point(
    aes(
      ideo_cat,
      pred
    ),
    shape = 21,
    size = 7.5,
    fill = "white", 
    data = t4 %>% 
      mutate(
      contrast = contrast %>%
        str_replace(" ", "\n")%>%
        factor(
          c("Misinformation\neffect",
            "Correction\neffect")
        )
      ) 
    ) +
  geom_text(
    aes(
      ideo_cat,
      pred,
      label = lab
      ),
    data = t4 %>% 
      mutate(
        contrast = contrast %>%
          str_replace(" ", "\n")%>%
          factor(
            c("Misinformation\neffect",
              "Correction\neffect")
          )
      ),
    size = 2.5
  ) +
  scale_color_grey(
    start = .65,
    end = .1,
    labels = c(
      "p >=.05",
      "p < .05"
      )
    ) +
  scale_x_discrete(
    labels = c("Left", "Mod.", "Right")
  ) +
  labs(y = "Difference on 5pt scale",
       x = "Ideology",
       color = "") +
  facet_grid(
    contrast ~ c2,
    space = "free_y",
    scale = "free_y"
  ) +
  theme(
    strip.text.y = element_text(angle = 0),
    legend.margin = margin(-.1, 0, 0, 0, "cm"),
    legend.position = "bottom"
  )

